package service.impl;

import dao.SysMMapper;
import enums.SysInfoEnum;
import exception.SysException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pojo.StuInfo;
import pojo.SysM;
import service.SysMService;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author jesse
 * @Date 2019/5/24 15:42
 * @Version 1.0
 */

@Service
@Slf4j
public class SysMServiceImpl  implements SysMService {


    @Autowired
    private SysMMapper sysMMapper;

    @Override
    public SysM getOne(String username) {
         SysM sysM = sysMMapper.getOne(username);
         if(sysM.getUsername().isEmpty()){
             throw new SysException(SysInfoEnum.ERROR);
         }
        return sysM;
    }

    @Override
    @Transactional
    public Integer insert(SysM sysM) {

        if (sysM.getId() == null) {
            log.warn("没有id，随机生成中");
            sysM.setId(UUID.randomUUID().toString());
        }
        if (Optional.ofNullable(sysM).isPresent()) {
            return  sysMMapper.add(sysM);
        }
        return SysInfoEnum.ERROR.getCode();
    }

    @Override
    public Integer delete(String username) {
        Integer result = sysMMapper.del(username);
        if(0 == result){
            throw new SysException(SysInfoEnum.ERROR);
        }
        return result;
    }

    @Override
    @Transactional
    public Integer update(SysM sysM) {
        Integer result = sysMMapper.change(sysM);
        if(0 == result){
            throw new SysException(SysInfoEnum.ERROR);
        }
        return result;
    }

    @Override
    @Transactional
    public List<SysM> getAll(){
        List<SysM> sysMS = sysMMapper.getAll();
        return sysMS;
    }

    @Override
    public List<SysM> getSysByArray(Integer currPage, Integer pageSize) {
        List<SysM> sysMS = sysMMapper.getAll();
        int firstIndex = (currPage -1 )*pageSize;
        int lastIndex = currPage * pageSize;
        if((sysMS.size()-firstIndex)<pageSize){
            sysMS =sysMS.subList(firstIndex,sysMS.size());
        }
        try{
            sysMS = sysMS.subList(firstIndex,lastIndex);
        }catch (Exception e){
            e.printStackTrace();
        }
        return sysMS;
    }
}
